package nl.justobjects.pushlet.pushmanager;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationHelper implements ApplicationContextAware {

	private static final Logger logger = LoggerFactory.getLogger(ApplicationHelper.class);
	private static String webRootPath;
	private static final Object webRootPathLock = new Object();
	private static ServletContext servletContext;
	private static ApplicationContext appContext;

	public static String getWebRootPath() {
		if (webRootPath != null) {
			return webRootPath;
		}
		synchronized (webRootPathLock) {
			if (webRootPath != null) {
				return webRootPath;
			}

			String path = servletContext.getRealPath("/");

			path = path.replace('\\', '/');

			if (path.charAt(0) != '/') {
				path = "/" + path;
			}

			if (path.charAt(path.length() - 1) == '/') {
				path = path.substring(0, path.length() - 1);
			}

			webRootPath = path;

			if (logger.isDebugEnabled()) {
				logger.debug("Get web root path: [{}].", webRootPath);
			}
		}

		return webRootPath;
	}

	public static Object getBean(String name) {
		return appContext.getBean(name);
	}

	public static ServletContext getServletContext() {
		return servletContext;
	}

	public static void setServletContext(ServletContext sc) {
		servletContext = sc;
	}

	@Override
	public void setApplicationContext(ApplicationContext ac) throws BeansException {
		appContext = ac;
	}

	public static void addApplicationContext(ApplicationContext ac) {
	}

}
